//
//  OAuthViewController.swift
//  sinaweibo
//
//  Created by IZEN on 16/3/10.
//  Copyright © 2016年 IZEN. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func setdefault() {
        let str = "document.getElementById('userId').value = 'leiggee@126.com', document.getElementById('passwd').value = 'oyonomg'"
        
        webView.stringByEvaluatingJavaScriptFromString(str)
    }
    
    override func loadView() {
        view = webView
        
        webView.opaque = false
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavBar()
        
        view.backgroundColor = UIColor.whiteColor()
        
        loadOAuthPage()
    }
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
    }
    
    private func loadOAuthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=3288835189" + "&redirect_uri=http://www.itcast.cn"
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
    }
    
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
    
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "默认账户", style: .Plain, target: self, action: "setdefault")
    }
}

extension OAuthViewController : UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        if urlString.containsString("code") {
            
            guard  let query = request.URL?.query else {
                return false
            }
            let codeStr = "code="
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            print(code)
            
            UserAccount.shareAccount.loadAccessToken(code,finished : { (isSuccess) -> () in
                if !isSuccess {
                    SVProgressHUD.showErrorWithStatus("世界上最遥远的距离就是没有网络")
                    return
                }
                //登录成功  销毁当前界面
                self.close()
                })
            return false
        }
        return true
    }
    
        
}


